package com.xinhe.web.reposity;

import com.xinhe.web.entity.TeamBuyOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.HashSet;
import java.util.List;

public interface TeamBuyOrderRepository  extends JpaRepository<TeamBuyOrder, Long> {

    @Query(value = "select count(1) from \n" +
            "(\n" +
            "select count(1),any_value(t1.f_team_goods_id) f_team_goods_id from tb_team_buy_order t1 \n" +
            "where t1.removed = 0 and t1.status in ('PAYED','SUCCESS') group by \n" +
            " t1.f_buyer_user_id\n" +
            ") t \n" +
            "where t.f_team_goods_id = ?1", nativeQuery = true)
    int querySumAmount(Long id);
    @Query(value = "select count(1) from tb_team_buy_order where f_team_goods_id = ?1 and status in ?2", nativeQuery = true)
    Integer countByTeamGoodsIdAndStatus(Long teamGoodsId, HashSet<String> statuses);

    @Query(value = "select * from tb_team_buy_order where status ='UNPAY' and TIMESTAMPDIFF(MINUTE,create_time,NOW()) > ?1", nativeQuery = true)
    List<TeamBuyOrder> findByTimeout(Integer teamTimeoutMinuteStr);


    @Query(value = "select * from tb_team_buy_order where removed = 0 and f_team_buy_id = ?1", nativeQuery = true)
    List<TeamBuyOrder> findByTeamByTimeout(Long id);

    @Query(value = "select * from tb_team_buy_order where removed = 0 and f_order_id = ?1", nativeQuery = true)
    TeamBuyOrder findByOrderId(Long orderId);

    @Modifying
    @Query(value = "update tb_team_buy_order set status = ?3 where removed = 0 and f_team_buy_id = ?1 and status = ?2", nativeQuery = true)
    void updateStatusByTeamBuyIdAndStatus(Long id, String beforeStatus, String afterStatus);

    @Query(value = "select * from tb_team_buy_order where removed = 0 and f_team_buy_id = ?1 and status='SUCESS'", nativeQuery = true)
    List<TeamBuyOrder> findByTeamBuyId(Long id);
    @Query(value = "select * from tb_team_buy_order where removed = 0 and f_team_buy_id = ?1 and f_buyer_user_id = ?2 and status='PAYED'", nativeQuery = true)
    TeamBuyOrder findOneByTeamBuyIdAndBuyerUserId(Long id, Long userId);
}
